<template>
  <BasicModal @register="modalRegister" :okText="SAVE" @ok="onSave" @cancel="onFinish">
    <BasicForm @register="formRegister" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { defineEmits, ref, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';

  import { save, update } from '../api';
  import { formSchemas as schemas } from '../schema';
  import { FormTypeEnum } from '/@/enums/formTypeEnum';
  import { UserListModel, UserSaveModel, UserUpdateModel } from '../model';
  import { FormData } from '/@/model/FormData';
  import { ADD, EDIT, SAVE } from '/@/constant';

  const emit = defineEmits(['onOk', 'register']);
  const typeRef = ref<FormTypeEnum>();
  const [modalRegister, { setModalProps, closeModal, changeLoading, changeOkLoading }] =
    useModalInner((data: FormData<UserListModel>) => {
      changeLoading(true);
      changeOkLoading(true);
      const { type, obj } = data;
      typeRef.value = type;
      setModalProps({
        title: type === FormTypeEnum.ADD ? ADD : `${EDIT}-${obj?.username}`,
      });
      if (type === FormTypeEnum.EDIT) {
        setFieldsValue({ ...obj });
      }
      changeLoading(false);
      changeOkLoading(false);
    });

  const [formRegister, { validate, resetFields, getFieldsValue, setFieldsValue }] = useForm({
    labelWidth: 120,
    schemas,
    showSubmitButton: false,
    showResetButton: false,
    actionColOptions: {
      span: 24,
    },
  });

  const onSave = async () => {
    changeLoading(true);
    changeOkLoading(true);
    const validateRes = await validate();

    if (validateRes) {
      try {
        const type = unref(typeRef);
        if (type === FormTypeEnum.ADD) {
          const user: UserSaveModel = getFieldsValue() as UserSaveModel;
          await save(user);
        }
        if (type === FormTypeEnum.EDIT) {
          const user: UserUpdateModel = getFieldsValue() as UserUpdateModel;
          await update(user);
        }
        onFinish();
        emit('onOk');
      } catch (e) {
        console.log(e);
      } finally {
        changeLoading(false);
        changeOkLoading(false);
      }
    }
  };
  const onFinish = () => {
    closeModal();
    resetFields();
  };
</script>

<style scoped></style>
